<template>
  <div class="categories-page">
    <el-row :gutter="20">
      <!-- 左侧：分类树 -->
      <el-col :span="10">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>分类树</h3>
              <el-button type="primary" size="small" @click="handleAddRoot">
                <el-icon><Plus /></el-icon>
                添加根分类
              </el-button>
            </div>
          </template>

          <!-- 搜索表单 -->
          <el-form :model="searchObject" inline class="search-form" style="margin-bottom: 15px">
            <el-form-item label="分类编码">
              <el-input
                v-model="searchObject.code"
                placeholder="请输入分类编码"
                clearable
                @keyup.enter="handleSearch"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label="分类名称">
              <el-input
                v-model="searchObject.name"
                placeholder="请输入分类名称"
                clearable
                @keyup.enter="handleSearch"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button size="small" @click="handleReset">
                重置
              </el-button>
            </el-form-item>
          </el-form>

          <el-input
            v-model="filterText"
            placeholder="过滤分类名称..."
            clearable
            style="margin-bottom: 15px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :highlight-current="true"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
            v-loading="loading"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div class="node-label">
                  <el-icon style="margin-right: 5px">
                    <Folder v-if="!node.isLeaf" />
                    <Document v-else />
                  </el-icon>
                  <span>{{ node.label }}</span>
                  <el-tag v-if="data.productCount" size="small" style="margin-left: 8px">
                    {{ data.productCount }}
                  </el-tag>
                </div>
                <div class="node-actions">
                  <el-button type="primary" size="small" text @click.stop="handleAdd(data)">
                    添加
                  </el-button>
                  <el-button type="warning" size="small" text @click.stop="handleEdit(data)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" text @click.stop="handleDelete(data)">
                    删除
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧：分类详情 -->
      <el-col :span="14">
        <el-card>
          <template #header>
            <h3>{{ selectedCategory ? '分类详情' : '请选择分类' }}</h3>
          </template>

          <div v-if="selectedCategory">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="分类ID">{{ selectedCategory.id }}</el-descriptions-item>
              <el-descriptions-item label="分类编码">{{ selectedCategory.code }}</el-descriptions-item>
              <el-descriptions-item label="分类名称">{{ selectedCategory.name }}</el-descriptions-item>
              <el-descriptions-item label="分类级别">
                <el-tag :type="getLevelType(selectedCategory.level)">
                  {{ getLevelName(selectedCategory.level) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="商品数量">
                <el-tag type="success">{{ selectedCategory.productCount || 0 }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="排序">{{ selectedCategory.sort }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="selectedCategory.status === '启用' ? 'success' : 'danger'">
                  {{ selectedCategory.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ selectedCategory.createTime }}</el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">
                {{ selectedCategory.description || '暂无描述' }}
              </el-descriptions-item>
            </el-descriptions>

            <!-- 关联商品列表 -->
            <el-divider>关联商品</el-divider>
            <el-table :data="relatedProducts" stripe max-height="300">
              <el-table-column prop="code" label="商品编码" width="120" />
              <el-table-column prop="name" label="商品名称" />
              <el-table-column prop="stock" label="库存" width="100" />
              <el-table-column prop="salePrice" label="售价" width="100">
                <template #default="{ row }">
                  ¥{{ row.salePrice }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-empty v-else description="请在左侧选择分类查看详情" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类编码" prop="code">
              <el-input v-model="categoryForm.code" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上级分类">
              <el-tree-select
                v-model="categoryForm.parentId"
                :data="categoryTree"
                :props="treeProps"
                :render-after-expand="false"
                placeholder="请选择上级分类（不选则为根分类）"
                clearable
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="categoryForm.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="分类图标">
          <el-select v-model="categoryForm.icon" placeholder="选择图标" style="width: 100%">
            <el-option label="文件夹" value="Folder" />
            <el-option label="文档" value="Document" />
            <el-option label="商品" value="Goods" />
            <el-option label="盒子" value="Box" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类描述">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Folder, Document } from '@element-plus/icons-vue'
import { defineStore } from 'pinia'
import { usePage } from '@/uses/usePage.js'
import request from '@/utils/request.js'

const treeRef = ref()
const formRef = ref()
const filterText = ref('')
const dialogVisible = ref(false)
const submitLoading = ref(false)
const selectedCategory = ref(null)

// 定义搜索状态存储
const searchStore = defineStore('categoryStore', {
  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 1000, // 树形结构一次性加载
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        code: ''
      }
    }
  }
})

const { searchObject } = searchStore()
const { pageData, searchList, sizeChange, pageChange, search, changeTableSort, loading } = usePage('/productCatalog/search', searchObject)

// 分类树数据 - 从接口数据构建树形结构
const categoryTree = computed(() => {
  return buildTree(pageData.data || [])
})

// 构建树形结构
const buildTree = (list) => {
  const map = {}
  const roots = []
  
  // 创建映射
  list.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })
  
  // 构建树
  list.forEach(item => {
    if (item.parentId === null || item.parentId === 0 || item.parentId === '') {
      roots.push(map[item.id])
    } else if (map[item.parentId]) {
      map[item.parentId].children.push(map[item.id])
    }
  })
  
  return roots
}

const treeProps = {
  children: 'children',
  label: 'name'
}

// 分类表单
const categoryForm = reactive({
  id: null,
  code: '',
  name: '',
  parentId: null,
  sort: 0,
  status: '启用',
  icon: 'Folder',
  description: ''
})

const formRules = {
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 关联商品列表
const relatedProducts = ref([])

// 加载关联商品
const loadRelatedProducts = async (categoryId) => {
  try {
    const res = await request.get(`/productCatalog/${categoryId}/products`)
    relatedProducts.value = res.data || []
  } catch (error) {
    console.error('加载关联商品失败:', error)
    relatedProducts.value = []
  }
}

const isEdit = computed(() => !!categoryForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑分类' : '新增分类')

// 监听搜索文本
watch(filterText, (val) => {
  treeRef.value.filter(val)
})

// 树节点过滤
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 获取分类级别名称
const getLevelName = (level) => {
  const map = { 1: '一级分类', 2: '二级分类', 3: '三级分类' }
  return map[level] || `${level}级分类`
}

// 获取分类级别类型
const getLevelType = (level) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'success' }
  return map[level] || 'info'
}

// 节点点击
const handleNodeClick = (data) => {
  selectedCategory.value = data
  loadRelatedProducts(data.id)
}

// 添加根分类
const handleAddRoot = () => {
  resetForm()
  categoryForm.parentId = null
  dialogVisible.value = true
}

// 添加子分类
const handleAdd = (data) => {
  resetForm()
  categoryForm.parentId = data.id
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (data) => {
  Object.assign(categoryForm, { ...data, parentId: data.parentId })
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (data) => {
  if (data.children && data.children.length > 0) {
    ElMessage.warning('该分类下有子分类，无法删除')
    return
  }

  if (data.productCount > 0) {
    ElMessage.warning('该分类下有商品，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await request.delete(`/productCatalog/${data.id}`)
    ElMessage.success('删除成功')
    searchList() // 刷新列表
    
    // 重置选中
    if (selectedCategory.value?.id === data.id) {
      selectedCategory.value = null
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 调用API
    if (isEdit.value) {
      await request.put('/productCatalog', categoryForm)
    } else {
      await request.post('/productCatalog', categoryForm)
    }

    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    searchList() // 刷新列表
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(categoryForm, {
    id: null,
    code: '',
    name: '',
    parentId: null,
    sort: 0,
    status: '启用',
    icon: 'Folder',
    description: ''
  })
  formRef.value?.clearValidate()
}

// 搜索分类
const handleSearch = () => {
  searchList()
}

// 重置搜索
const handleReset = () => {
  searchObject.name = ''
  searchObject.code = ''
  searchObject.no = 1
  searchList()
}
</script>

<style scoped>
.categories-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.node-label {
  display: flex;
  align-items: center;
  flex: 1;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}
</style>
